#include <iostream>
#include <Windows.h>

// 函数声明
void gaussianElimination(float** A, float* B, int n);
void forwardElimination(float** A, float* B, int n);

int main() {
    const int N = 32; // 矩阵大小为 N x N
    const int MAX_RANDOM = 100; // 随机数上限

    // 分配内存
    float** A = new float*[N];
    for (int i = 0; i < N; ++i) {
        A[i] = new float[N];
    }
    float* B = new float[N];

    // 初始化矩阵和向量为100以内的随机数
    srand(static_cast<unsigned int>(time(nullptr)));
    for (int i = 0; i < N; ++i) {
        B[i] = static_cast<float>(rand() % MAX_RANDOM);
        for (int j = 0; j < N; ++j) {
            A[i][j] = static_cast<float>(rand() % MAX_RANDOM);
        }
    }

    // 计时开始
    LARGE_INTEGER freq, head, tail;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&head);

    // 执行高斯消去法
    gaussianElimination(A, B, N);

    // 计时结束
    QueryPerformanceCounter(&tail);

    // 计算执行时间
    double Mytime = static_cast<double>(tail.QuadPart - head.QuadPart) * 1000.0 / freq.QuadPart;

    // 输出执行时间
    std::cout << "高斯消去法执行时间: " << Mytime << " ms" << std::endl;

    // 释放内存
    for (int i = 0; i < N; ++i) {
        delete[] A[i];
    }
    delete[] A;
    delete[] B;

    return 0;
}

// 高斯消去法
void gaussianElimination(float** A, float* B, int n) {
    forwardElimination(A, B, n);

    // 回代操作
    for (int k = n - 1; k >= 0; --k) {
        B[k] /= A[k][k];
        A[k][k] = 1.0f;
        for (int i = k - 1; i >= 0; --i) {
            B[i] -= A[i][k] * B[k];
            A[i][k] = 0.0f;
        }
    }
}


// 前向消元
void forwardElimination(float** A, float* B, int n) {
    for (int k = 0; k < n - 1; ++k) {
        for (int i = k + 1; i < n; ++i) {
            float factor = A[i][k] / A[k][k];
            for (int j = k; j < n; ++j) {
                A[i][j] -= factor * A[k][j];
            }
            B[i] -= factor * B[k];
        }
    }
}
